new Vue({
    el: '#app',
    mixins: [Save],//组件配置文件，路径/utils/components.js
    data() {
        return {
            acquisition_unitprice: {},
            dataForm: {
                Amount: '0',
                Quantity: '0',
                Detailed_Address: '',
                Trading_SerialNumber: '',
                Shipment_Method_SerialNumber: '',
            },
            Trading_SerialNumber: [],
            Payment_Method_SerialNumber: [],
            Shipment_Method_SerialNumber: [],
            Transport_Method_SerialNumber: [],
            article_info: [], // 可选商品
            transport_method: [], // 运输方式
            shipment_method: [], // 装运方式
            payment_method: [], // 付款方式
            article_unit: [], // 单位
            enterprise_info: [],// 企业
            enterprise_info1: [],// 企业1
            city: [],
            trading: [],// 付款类型
        }
    },
    mounted() {
        /**
         * 组件配置文件中自动执行方法
         * 1.this.init(); //初始化文件
         * 2.this.getData(); //仅修改时执行，根据BOM配置属性查询
         */
        this.getList();
    },
    methods: {
        // Save 混入在完成 Modify 模式的数据回填后会调用该方法
        documentLoadFinished() {
            // 依赖 dataForm 的初始化移动到这里，确保回填完成后再取数
            this.getList();
        },
        getList() { // 初始化数据
            // 在修改模式下，nodeKey为“Acquisition_Order_SerialNumber”，不应直接覆盖报价编号
            // 优先使用从主表读取到的报价编号（由 Save.getData 填充到 dataForm）
            const unitPriceId = this.dataForm.Acquisition_Unit_Price_SerialNumber || this.nodeKey;
            // 查询主数据
            httpRequest({
                url: '/generalBusiness/queryMultiTableByCondition',
                data: {
                    Data: JSON.stringify([{
                        tableName: 'acquisition_unitprice',
                        Condition: utf8ToBase64(`Acquisition_Unit_Price_SerialNumber='${unitPriceId}'`),
                    }, {
                        tableName: 'acquisition_unitprice_mapping_payment',
                        Condition: utf8ToBase64(`Row_Status='0' AND Acquisition_Unit_Price_SerialNumber='${unitPriceId}'`),
                    }, {
                        tableName: 'acquisition_unitprice_mapping_shipment',
                        Condition: utf8ToBase64(`Row_Status='0' AND Acquisition_Unit_Price_SerialNumber='${unitPriceId}'`),
                    }, {
                        tableName: 'acquisition_unitprice_mapping_trading',
                        Condition: utf8ToBase64(`Row_Status='0' AND Acquisition_Unit_Price_SerialNumber='${unitPriceId}'`),
                    }, {
                        tableName: 'acquisition_unitprice_mapping_transport',
                        Condition: utf8ToBase64(`Row_Status='0' AND Acquisition_Unit_Price_SerialNumber='${unitPriceId}'`),
                    },{
                        tableName: 'article_info',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'transport_method',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'shipment_method',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'payment_method',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'article_unit',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'enterprise_info',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }])
                },
            }).then(data => {
                const { acquisition_unitprice, acquisition_unitprice_mapping_payment, acquisition_unitprice_mapping_shipment, acquisition_unitprice_mapping_trading, acquisition_unitprice_mapping_transport, article_info, transport_method, shipment_method, payment_method, article_unit, enterprise_info } = data || {};
                const first = (Array.isArray(acquisition_unitprice) && acquisition_unitprice[0]) ? acquisition_unitprice[0] : {};
                this.acquisition_unitprice = first;
                this.Trading_SerialNumber = (acquisition_unitprice_mapping_trading || []).map(i => i.Trading_SerialNumber);
                this.Payment_Method_SerialNumber = (acquisition_unitprice_mapping_payment || []).map(i => i.Payment_Method_SerialNumber);
                this.Shipment_Method_SerialNumber = (acquisition_unitprice_mapping_shipment || []).map(i => i.Shipment_Method_SerialNumber);
                this.Transport_Method_SerialNumber = (acquisition_unitprice_mapping_transport || []).map(i => i.Transport_Method_SerialNumber);
                this.article_info = article_info || [];
                this.transport_method = transport_method || [];
                this.shipment_method = shipment_method || [];
                this.payment_method = payment_method || [];
                this.article_unit = article_unit || [];
                this.enterprise_info = enterprise_info || [];
                this.dataForm.Quantity = first.Start_Quantity || this.dataForm.Quantity || '0';
                this.changeQuantity(this.dataForm.Quantity);
            }).catch(xhr => {
                this.$message({
                    message: '系统错误，请联系开发者!',
                    type: 'error'
                })
            })

            httpRequest({
                url: '/generalBusiness/generalQueryBySQLSerialNumber',
                data: {
                    SQLSerialNumber: 'f_user_mapping_enterprise',
                    Condition: utf8ToBase64(getCookie('user')),
                    ExtensionCondition: ''
                }
            }).then(data => {
                this.enterprise_info1 = data || [];
                const currentEnterpriseId = (Array.isArray(data) && data[0]) ? data[0].Enterprise_Info_SerialNumber : '';
                this.$set(this.dataForm, 'Enterprise_Info_SerialNumber', currentEnterpriseId);
            }).catch(xhr => {
                this.$message({
                    message: '系统错误，请联系开发者!',
                    type: 'error'
                })
            })

            // 地址 
            $.ajax({
                url: absolutepath() + 'admin/data/dtree.json',
                type: 'GET',
                success: (data) => {
                    this.city = data;
                },
            })

            $.ajax({
                url: absolutepath() + 'admin/data/trading.json',
                type: 'GET',
                success: (data) => {
                    this.trading = data;
                },
            })
        },
        changeCity(val) {
            this.dataForm.ProvinceNumber = val ? (val.substring(0, 2) + '0000') : '';
            this.dataForm.CityNumber = val ? (val.substring(0, 4) + '00') : '';
            this.dataForm.Detailed_Address = '';
        },
        changeChildDataForm(val, formName) { //付款方式
            this[formName] = val.map(i => {
                let obj = new Object();
                obj[formName] = i
                return obj;
            })
        },
        changeQuantity(val) { //销售数量
            const qty = Number(val || 0);
            const unitPrice = Number((this.acquisition_unitprice && this.acquisition_unitprice.Unit_Price) || 0);
            if (isNaN(qty) || isNaN(unitPrice)) {
                this.dataForm.Amount = 0;
                return;
            }
            this.dataForm.Amount = accMul(qty, unitPrice);
        },
        async handleSubmit() { //点击提交
            const allValid = await this.validateAllForms();
            if (allValid) {
                // this.loading = true;
                try {
                    const acquisition_unitprice = deepClone(this.acquisition_unitprice);

                    // 一致性校验：扣减前校验剩余量是否足够
                    const reqQty = Number(this.dataForm.Quantity || 0);
                    const remainQty = Number(acquisition_unitprice.Remain_Quantity || 0);
                    if (isNaN(reqQty) || reqQty <= 0) {
                        this.$message.error('交易数量无效');
                        this.loading = false;
                        return;
                    }
                    if (remainQty < reqQty) {
                        this.$message.error('剩余量不足，无法提交报价');
                        this.loading = false;
                        return;
                    }

                    //计算剩余数量
                    acquisition_unitprice.Remain_Quantity = accSub(acquisition_unitprice.Remain_Quantity, this.dataForm.Quantity);
                    acquisition_unitprice.Sales_Quantity = accAdd(acquisition_unitprice.Sales_Quantity, this.dataForm.Quantity);

                    const lJSONObject_DataSet = this.generateStructure();

                    lJSONObject_DataSet['Modify'] = { acquisition_unitprice: [acquisition_unitprice] };

                    httpRequest({
                        contentType: 'JSON',
                        url: '/generalBusiness/generalSaveByRequestBody',
                        data: JSON.stringify({
                            Data: lJSONObject_DataSet
                        })
                    }).then(res => {
                        if (res.Status == "success") {
                            this.$message.success("提交成功");
                            window.location.href = './index.html';
                        } else {
                            this.$message.error("提交失败，请重试！");
                        }
                    }).catch(xhr => {
                        this.$message.error("系统错误，请联系开发者!")
                    }).finally(() => {
                        this.loading = false;
                    })
                } catch (error) {
                    console.error(error);
                    this.$message.error("系统错误，请联系开发者!")
                    this.loading = false;
                }
            } else {
                this.$message({
                    message: '存在未填写的必填项！',
                    type: 'warning'
                });
            }
        },
        async handleResubmit() { // 修改并重新提交：状态重置为待审核
            const allValid = await this.validateAllForms();
            if (!allValid) {
                this.$message({ message: '存在未填写的必填项！', type: 'warning' });
                return;
            }
            try {
                // 以提交页的修改模式为准，nodeKey 为对应订单主键
                const data = await generalApi.generalQueryByTableNameWithOriginal({
                    Data: 'acquisition_order',
                    Condition: `Acquisition_Order_SerialNumber='${this.nodeKey}'`
                });
                if (!Array.isArray(data) || data.length !== 1) {
                    this.$message.error('未找到报价订单或存在重复记录');
                    return;
                }
                const origin = data[0];
                // 避免使用页面的 dataForm 覆盖原始的报价编号字段
                const updated = { 
                    ...origin, 
                    ...this.dataForm, 
                    Acquisition_Order_SerialNumber: this.nodeKey,
                    Acquisition_Unit_Price_SerialNumber: origin.Acquisition_Unit_Price_SerialNumber
                };
                // 重置为待审核
                updated.Row_Status = '0';

                const dataset = {
                    Modify: { acquisition_order: [updated] },
                    Add: {
                        base_operation_log: [{
                            Operation_Type: '0',
                            Operation_Path: getRelativePath(),
                            Operation_Description: '报价修改并重新提交（状态置为待审核）',
                            Operation_Main: JSON.stringify({
                                Acquisition_Order_SerialNumber: this.nodeKey,
                                Acquisition_Unit_Price_SerialNumber: origin.Acquisition_Unit_Price_SerialNumber,
                                Action: 'modify_resubmit_quote'
                            }),
                            Operation_Interface: 'generalSaveByRequestBody',
                            Operation_IP: getIpAddress()
                        }]
                    }
                };

                const res = await generalApi.generalSaveByRequestBody({ Data: dataset });
                if (res && (res.Status === 'success' || (Array.isArray(res) && res.every(r => r.Status === 'success')))) {
                    this.$message.success('已重新提交该报价');
                    window.location.href = './index.html';
                } else {
                    const msg = (res && (res.Message || res.Error || res.msg)) || '保存失败';
                    this.$message.error(msg);
                }
            } catch (error) {
                console.error(error);
                this.$message.error('系统错误，请联系开发者!');
            }
        }
    }
})